import json
import requests
from scripts.config_reader import ConfigReader
from scripts.import_data import SimpleDB


class RequestHandler:
    def __init__(self):
        config = ConfigReader().config
        self.base_url = config.get('api', 'base_url')
        self._session = requests.Session()

        # 更安全的 headers 解析
        headers = config.get('api', 'headers', fallback="{}")
        try:
            self._session.headers.update(json.loads(headers))
        except json.JSONDecodeError:
            self._session.headers.update({})

        self._session.verify = config.getboolean('api', 'verify_ssl')
        self._session.timeout = config.getint('api', 'timeout')

    def process_requests(self):
        with ConfigReader().get_cursor() as conn:
            for idx, row in enumerate(SimpleDB(conn).select('gdyh'), 1):
                if not (info := self._extract_request_info(row)):
                    continue

                if (result := self._send_request(**info)) and result['success']:
                    self._compare_response(result, info)

    def _extract_request_info(self, row):
        try:
            return {
                'url': self.base_url + row[4],
                'method': row[3].lower(),
                'data': row[5],
                'expected_output': row[6]
            }
        except (IndexError, TypeError):
            return None

    def _send_request(self, url, method, data,**kwargs):
        try:
            response = getattr(self._session, method)(url, data=data)
            response.raise_for_status()
            return {
                'success': True,
                'status_code': response.status_code,
                'response': response.json() if response.text else None
            }
        except requests.exceptions.RequestException:
            return None

    def _compare_response(self, result, info):
        try:
            # 更安全的 expected_output 解析
            expected = info['expected_output']
            if isinstance(expected, str):
                try:
                    expected = json.loads(expected)
                except json.JSONDecodeError:
                    expected = expected  # 保持原样

            if result['response'] != expected:
                print(
                    f"{result['status_code']}\n实际结果与预期结果不同\nExpected: {expected}\nActual: {result['response']}")
        except Exception:
            pass


if __name__ == '__main__':
    RequestHandler().process_requests()